package com.achievo.reportserver.mq;

import java.io.File;

import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.TextMessage;

import org.apache.log4j.Logger;

import com.achievo.reportserver.config.ConfigUtils;
import com.achievo.reportserver.config.ReportConfigStore;
import com.achievo.reportserver.config.ReportRoot;


/**
 * 
 * Report Server
 * write at Jan 21, 2010
 * @author <a href="mailto:chinaoryx@gmail.com">Hyman.Zhang (Zhang Haipeng)</a>
 * @version 1.0
 * 
 *
 */
public class ReportConfigParserListener implements MessageListener {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger
			.getLogger(ReportConfigParserListener.class);

	public void onMessage(Message message) {
		if (logger.isDebugEnabled()) {
			logger.debug("onMessage(Message=" + message + ") - start");
		}

		try {
			if (message instanceof TextMessage) {
				TextMessage txtMsg = (TextMessage) message;
				String msg = txtMsg.getText();
				String filePath = txtMsg.getStringProperty("filepath");
				ConfigUtils utils = new ConfigUtils();
				
				
				if ("fileCreate".equalsIgnoreCase(msg)) {
					ReportRoot root = utils.parseConfigFile(new File(filePath));
					ReportConfigStore.onNewUpdateFile(filePath, root);
				} else if ("fileChange".equalsIgnoreCase(msg)) {
					ReportRoot root = utils.parseConfigFile(new File(filePath));
					ReportConfigStore.onNewUpdateFile(filePath, root);
				} else if ("fileDelete".equalsIgnoreCase(msg)) {
					ReportConfigStore.onDeleteFile(filePath);
				} else if ("jasperUpdate".equals(msg)){
					ReportConfigStore.refreshStore();
				}

			}
		} catch (Exception e) {
			logger.error("onMessage(Message) - exception ignored", e);		
		}

		if (logger.isDebugEnabled()) {
			logger.debug("onMessage(Message=" + message + ") - end");
		}
	}

}
